<template>
	<div class="box-container" v-loading="sLoading">
		<div class="box-content">
			<div class="addBoxTop">
				<div v-if="detailsId">
					<span class="font_size20">{{ activityTypeDictMap[objectForm.type] || '' }}详细</span>
				</div>
				<div v-else class="font_size20">投票/报名</div>
			</div>
			<div class="basc-info">
				<Descriptions :column="3" title="">
					<el-descriptions-item label="使用云店">{{ objectForm.shop_name || '--' }}</el-descriptions-item>
					<el-descriptions-item label="活动标题">{{ objectForm.title || '--' }}</el-descriptions-item>
					<el-descriptions-item label="活动类型">{{ activityTypeDictMap[objectForm.type] || '--'
					}}</el-descriptions-item>
					<el-descriptions-item
						:label="activityTypeDictMap[objectForm.type] ? activityTypeDictMap[objectForm.type] + '人数' : '人数'">{{
							objectForm.num_od || '--'
						}}</el-descriptions-item>
					<el-descriptions-item
						:label="activityTypeDictMap[objectForm.type] ? activityTypeDictMap[objectForm.type] + '总额' : '总额'">
						<span class="font_green">￥{{ objectForm.total_od || '--'
						}}</span> </el-descriptions-item>
					<el-descriptions-item label="活动时效">{{ objectForm.time_from_txt || '--' }} 至 {{
						objectForm.time_to_txt ||
						'--' }}</el-descriptions-item>
					<el-descriptions-item label="活动海报">
						<div class="font_bule under-line" @click="qrPosterFun" v-if="objectForm.share_paper_url">
							去扫码分享 </div>
						<span v-else> -- </span>
					</el-descriptions-item>

					<el-descriptions-item label="活动负责人姓名">
						<span> {{ objectForm.me_info && objectForm.me_info.adm_uname || '--' }} </span>
					</el-descriptions-item>
					<el-descriptions-item label="活动负责人电话">
						<span> {{ objectForm.me_info && objectForm.me_info.adm_phone || '--' }} </span>
					</el-descriptions-item>
					<!-- <el-descriptions-item label="云店二维码">
						<span class="font_bule under-line" @click="qrCodeFun"
							v-if="objectForm.me_info && objectForm.me_info.qrcode"> 查看 </span>
						<span v-else> -- </span>
					</el-descriptions-item> -->
					<el-descriptions-item label="活动店名/场地名称">
						<span>{{ objectForm.me_info && objectForm.me_info.addname || '--' }}</span>
					</el-descriptions-item>
					<el-descriptions-item label="活动描述">{{ objectForm.desc || '--' }}</el-descriptions-item>
				</Descriptions>
				<div class="flex_between mt5" v-if="objectForm.obj_ls && objectForm.obj_ls.length > 0">
					<div style="flex: 1;">
						<h3>{{ activityTypeDictMap[objectForm.type] ? activityTypeDictMap[objectForm.type] + '对象' :
							'对象' }}</h3>
						<div class="obj-ls-box mt5">
							<div class="obj-ls-item flex_row" v-for="tuser in objectForm.obj_ls" :key="tuser.id">
								<el-avatar size="small" :src="tuser.img"></el-avatar>
								<div>
									<p class="font_size16 ml10">{{ tuser.title }}</p>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
			<div>
				<div class="mb10 mt10 flex_row">
					<h3>参与{{ activityTypeDictMap[objectForm.type] || '' }}用户</h3>
					<el-button type="primary" size="mini" @click="exportUserList" v-if="userList && userList.length > 0"
						style="margin-left: 10px;"> 导出{{ activityTypeDictMap[objectForm.type] || '' }}用户 </el-button>
				</div>
				<div>
					<el-row :gutter="12">
						<template v-if="userList.length > 0 && objectForm.type == 1">
							<LoadList :loading="listLoading" :no-more="noMore" :containerHeight="containerHeight"
								:distance="100" @load-more="loadMoreData">
								<div :style="{ overflow: 'auto' }">
									<div class="card_box" v-for="(item, index) in userList" :key="index">
										<el-col :span="8">
											<el-card shadow="always">
												<div class="flex_between" @click="handleClick(item)">
													<div class="flex_row">
														<div v-if="item && item.avatar" class="obj-avatar-box">
															<img class="obj-avatar" :src="item.avatar" alt="">
														</div>
														<div class="ml10">
															<p class="font_size14 bold">
																<span>{{ item.name || '未知' }}</span>
																<span v-if="item.rname">({{ item.rname }})</span>
															</p>
															<p class="font_size12">{{ item.cellphone || '--' }}</p>
															<p class="font_size12 font_red">￥<span class="bold">{{
																item.amount
																||
																0.00 }}</span></p>
															<p class="font_size12"> {{ item.atime_txt || '--' }}</p>
														</div>
													</div>
													<div class="tp_obj ml10 flex_center_column" v-if="item && item.obj">
														<p class="font_size14 bold">投票对象</p>
														<div class="obj-avatar-box">
															<img v-if="item && item.obj && item.obj.img"
																class="obj-avatar" :src="item.obj.img" alt="">
														</div>
														<p class="font_size12 ellipsis flex_center"
															style="width: 100px;">{{
																item.obj && item.obj.title || '--' }}</p>
													</div>
												</div>
											</el-card>
										</el-col>
									</div>
								</div>
							</LoadList>
						</template>
						<template v-if="userList.length > 0 && objectForm.type == 2">
							<LoadList :loading="listLoading" :no-more="noMore" :containerHeight="containerHeight"
								:distance="100" @load-more="loadMoreData">
								<div :style="{ overflow: 'auto' }">
									<div class="card_box" v-for="(item, index) in userList" :key="index"
										@click="handleClick(item)">
										<el-col :span="8">
											<el-card shadow="always">
												<div class="flex_between">
													<div class="flex_row">
														<div v-if="item && item.avatar" class="obj-avatar-box">
															<img class="obj-avatar" :src="item.avatar" alt="">
														</div>
														<div class="ml10">
															<p class="font_size14 bold">
																<span>{{ item.name || '未知' }}</span>
																<span v-if="item.rname">({{ item.rname }})</span>
															</p>
															<p class="font_size12">{{ item.cellphone || '--' }}</p>
															<p class="font_size12 font_red">￥<span class="bold">{{
																item.amount
																||
																0.00 }}</span></p>
														</div>
													</div>
													<p class="font_gray"> {{ item.atime_txt || '--' }}</p>
												</div>
											</el-card>
										</el-col>
									</div>
								</div>
							</LoadList>
						</template>
						<empty v-if="userList.length == 0"></empty>
					</el-row>
				</div>
			</div>
		</div>
		<div class="footer-content" v-if="operations.length > 0">
			<footer-bottom :operations="operations" @operation="handleOperation" />
		</div>
		<bigImageMask ref="bigImageRef"></bigImageMask>

		<ayjDrawer title="用户详情" width="60%" ref="ayjDrawerRef" :slotFooter="true" @closeFun="handleClose">
			<template v-if="customerId">
				<customersThree ref="customersThreeRef" :xsgf="15" :isDrawerOpen="true" :customerId="customerId">
				</customersThree>
			</template>
			<template v-else>
				<empty></empty>
			</template>
		</ayjDrawer>

		<ayjDialog title="活动海报" width="25%" ref="posterRef" top="5vh" :slotFooter="false" @closeFun="posterClose">
			<div class="flex_center_column poster-container" v-loading="posterLoading">
				<h4 class="mb10"> 请扫二维码再分享 </h4>
				<el-image v-if="objectForm.tpl_ad && objectForm.tpl_ad.length > 0" :src="objectForm.tpl_ad[0].obj_img"
					class="poster-bg" fit="fill" :style="{
						width: posterW + 'px',
						height: posterH + 'px',
					}" />
				<mu-canvas ref="shareRef" :width="posterW" :height="posterH * 0.35" unit="px" backgroundColor="#fff"
					:elementList="elementList" :auto="false">
				</mu-canvas>
			</div>
		</ayjDialog>

	</div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, getCurrentInstance, watch, computed, nextTick } from '@vue/composition-api'
import { useAppStore } from '@/store/piniaStore'
import config from "@/js/conf/Config.js"
import timeList from "@/components/marketingMenu/timeList.vue"
import uploadPic from "@/js/upload/UploadPic.js"
import staticConst from "@/js/const/StaticConst.js"
import { activityDict } from '@/utils/dict.js'
import Descriptions from "@/components/commV2/Description/descriptions.vue"
import bigImageMask from "@/components/goods/bigImageMask.vue";
import empty from "@/components/comm/empty.vue";
import LoadList from "@/components/commV2/LoadList/index.vue";
import FooterBottom from "@/components/commV2/FooterBottom/index.vue";
import customersThree from '@/components/customers/CustomersThree.vue';
import muCanvas from '@/components/poster/mu-canvas.vue';
import ExcelExporter from '@/utils/excelExport.js'


// 获取当前组件实例
const { proxy } = getCurrentInstance()

// Pinia store
const piniaStore = useAppStore()

const props = defineProps({
	detailID: {
		type: String,
		default: "",
	},
})

const activityTypeDictMap = ref(activityDict.activityTypeDictMap)

const emit = defineEmits(['editStopTpBmFun'])

const sLoading = ref(false)
const bigImageRef = ref(null)

const objectForm = ref({})

// 未开始：编辑
// 进行中：停止，编辑

const musicList = ref([])
const userList = ref([])

// 导出用户列表
const exportUserList = async () => {
	const res = await proxy.$api({
		url: config.YY_EVENT_ULS_EXPORT, data: {
			id: props.detailID,
			pfrom: pfrom.value,
			pnum: pnum.value,
			st: 1, // 状态：1有效的，8伪造的
		}
	})
	if (res.status == 1) {
		downloadExcel(res.data)
	} else {
		proxy.$message.error('导出失败')
	}
}

// 自定义表头映射
const downloadExcel = async (data) => {

	// 根据 title 表头循环，从 list 数组对象中取值，生成新的 list
	let newList = data.ls.map(item => {
		let newItem = {}
		// 循环 title 对象的每个键
		for (let key in data.title) {
			// 如果 list 中的 item 包含这个字段，则提取其值
			if (item.hasOwnProperty(key)) {
				newItem[key] = item[key]
			} else {
				// 如果没有这个字段，设置为空字符串或默认值
				newItem[key] = ''
			}
		}
		return newItem
	})
	try {
		const success = await ExcelExporter.export(
			newList, // 数据
			`${data.sheet_title}.xlsx`,
			data.title // 表头
		)
		if (success) {
			proxy.$message.success('成功导出表格,请保存')
		}
	} catch (error) {
		proxy.$message.error('导出失败：' + error?.message)
	}
}

// 状态 1未开始  2进行中  3已失效  7已删除
const operations = computed(() => {
	return objectForm.value.status == 1 ? [
		{ text: '编辑', type: 'edit', class: 'primary' }
	] : objectForm.value.status == 2 ? [
		{ text: '停止', type: 'stop', class: 'danger' },
		{ text: '编辑', type: 'edit', class: 'primary' }
	] : objectForm.value.status == 3 ? [
		{ text: '重启', type: 'edit', class: 'primary' }
	] : []
})

const ayjDrawerRef = ref(null)
const customersThreeRef = ref(null)
const customerId = ref(null)
const posterW = ref(360)
const posterH = ref(450)
const posterLoading = ref(false)
const elementList = computed(() => {
	return {
		// https://cdn-test.imiyun.com/d/cp25/avatar/dc652f9bfd166f1755e9abcb9cf3c0d8.jpg?&x-oss-process=image/resize,m_lfit,w_1280
		images: [ //图片对象
			{
				path: '/static/images/qian_btn.png', //图片路径[必填] objectForm.value.shop_logo
				dx: 0, //左上角x轴[必填]
				dy: 0, //左上角y轴[必填]
				dWidth: posterW.value, //宽度[必填]
				dHeight: (posterH.value * 0.2).toFixed(0), //高度[必填]
				sx: 0, //绘画的宽度[选填]
				sy: 0, //绘画的高度[选填]
			}
		],
		text: [ //渲染文字
			{
				value: `「${objectForm.value.shop_name}」邀请您一起`, //渲染的文字
				color: "#111", //文字颜色[选填]
				size: "15", //大小[选填]
				font: "PingFang SC-Regular, PingFang SC;", //字体[选填]
				x: 0, //左上角x轴[必填]
				y: 30, //左上角y轴[必填]
				// backgroundColor: "#ffffff", //背景色
				maxWidth: "", //字体最大宽度
				maxHeight: "", //字体最大高度
			},
			{
				value: `参加「${objectForm.value.title}」`, //渲染的文字
				color: "#111", //文字颜色[选填]
				size: "15", //大小[选填]
				font: "PingFang SC-Regular, PingFang SC;", //字体[选填]
				x: 5, //左上角x轴[必填]
				y: 55, //左上角y轴[必填]
				// backgroundColor: "#ffffff", //背景色
				maxWidth: "", //字体最大宽度
				maxHeight: "", //字体最大高度
			},
			{
				value: `预留金额：￥${objectForm.value.price || '0.00'}`, //渲染的文字
				color: "#c00", //文字颜色[选填]
				size: "15", //大小[选填]
				font: "PingFang SC-Regular, PingFang SC;", //字体[选填]
				x: 5, //左上角x轴[必填]
				y: 90, //左上角y轴[必填]
				// backgroundColor: "#ffffff", //背景色
				maxWidth: "", //字体最大宽度
				maxHeight: "", //字体最大高度
			},
			{
				value: `商品价值：￥${objectForm.value.price2 || '0.00'}`, //渲染的文字
				color: "#999", //文字颜色[选填]
				size: "12", //大小[选填]
				font: "PingFang SC-Regular, PingFang SC;", //字体[选填]
				x: 5, //左上角x轴[必填]
				y: 110, //左上角y轴[必填]
				// backgroundColor: "#ffffff", //背景色
				maxWidth: "", //字体最大宽度
				maxHeight: "", //字体最大高度
			},
			{
				value: `长按识别图中二维码 马上参与吧~`, //渲染的文字
				color: "#333", //文字颜色[选填]
				size: "12", //大小[选填]
				font: "PingFang SC-Regular, PingFang SC;", //字体[选填]
				x: 5, //左上角x轴[必填]
				y: 145, //左上角y轴[必填]
				// backgroundColor: "#ffffff", //背景色
				maxWidth: "", //字体最大宽度
				maxHeight: "", //字体最大高度
			}
		],
		qr: [ //渲染的二维码
			{
				url: objectForm.value.share_paper_url, //二维码文字[必填]
				dx: 258, //左上角x轴[必填]
				dy: 44, //左上角y轴[必填]
				size: 100, //二维码大小
				color: "#333333", //二维码前景色
				backgroundColor: "#ffffff" //二维码背景色
			}
		]
	}
})


const handleClick = (item) => {
	console.log("item=", item)
	// piniaStore.setCustomersDrawerStatus(false)
	ayjDrawerRef.value.open()
	customerId.value = item.customerid || '-1' //item.id 10 263  51
}

const editTpBmFun = (type) => {
	emit('editStopTpBmFun', {
		type: type,
		id: props.detailID
	})
}
const handleOperation = (type) => {
	console.log("type=", type)
	switch (type) {
		case 'delete':
			// Handle delete
			break;
		case 'copy':
			// Handle copy
			break;
		case 'edit':
			// Handle edit
			editTpBmFun('edit')
			break;
		case 'stop':
			stopFun('stop')
			break;
	}
};

const stopFun = (type) => {
	proxy.$confirm("确定要停止该活动?", "温馨提醒", {
		confirmButtonText: "停止",
		cancelButtonText: "取消",
		type: "warning",
	})
		.then(() => {
			let param = {
				act: type,
				id: props.detailID,
				status: 3,
			}
			proxy.$api({ url: config.YY_EVENT_SAVE, data: param }).then(res => {
				if (res.status == 1) {
					proxy.$message.success('停止成功')
					editTpBmFun(type)
					objectForm.value.status = 3
				}
			})
		})
		.catch(() => { });
}

const posterRef = ref(null)
const qrPosterFun = () => {
	posterRef.value.open()
	posterLoading.value = true
	setTimeout(() => {
		nextTick(() => {
			startGenerate()
		})
	}, 800);
}

// 开始生成
const base64Url = ref('')
const shareRef = ref(null)
const startGenerate = () => {
	console.log('开始生成海报流程...');
	posterLoading.value = true
	if (!shareRef.value) {
		console.log('Canvas组件未找到，重试中...');
		setTimeout(() => {
			startGenerate();
		}, 500);
		return;
	}
	generatePoster();
}

// 生成海报
const generatePoster = async () => {
	console.log('执行海报生成...');
	try {
		// 等待canvas准备
		await new Promise(resolve => setTimeout(resolve, 800));
		// 执行绘制
		await redraw();
		// // 获取图片
		// const posterUrl = await getImgSrc();
		// console.log("posterUrl=", posterUrl)
		// if (posterUrl) {
		// 	base64Url.value = posterUrl;
		// 	console.log('海报生成成功');
		// } else {
		// 	console.error('获取海报URL失败');
		// }
	} catch (error) {
		console.error('生成海报出错:', error);
		uni.showToast({
			title: '生成失败，请重试',
			icon: 'none'
		});
	}
	uni.hideLoading();
}

const redraw = () => {
	if (shareRef.value) {
		// Vue3 取不到 $refs.xxx.redraw，手动兼容
		if (shareRef.value.redraw) {
			shareRef.value.redraw();
			posterLoading.value = false
		} else if (window.__MU_CANVAS_EXPOSE__) {
			window.__MU_CANVAS_EXPOSE__(shareRef.value).redraw();
			posterLoading.value = false
		}
	} else {
		posterLoading.value = false
	}
}

const getImgSrc = async () => {
	console.log("shareRef.value=", shareRef.value)
	if (!shareRef.value) {
		console.error('Canvas组件未找到');
		return null;
	}
	try {
		const url = await shareRef.value.getImgSrc();
		return url;
	} catch (error) {
		console.error('获取图片失败:', error);
		return null;
	}
}

const posterClose = () => {
	posterRef.value.close()
}

const qrCodeFun = () => {
	const qrcodeUrl = objectForm.value.me_info.qrcode
	console.log("qrcodeUrl=", qrcodeUrl)
	if (qrcodeUrl) {
		bigImageRef.value.toggleBillsStateMask("show", [qrcodeUrl], 0)
		bigImageRef.value.title = '云店二维码'
	} else {
		proxy.$message.error('云店二维码不存在')
	}
}

const getMusicList = async () => {
	const param = {}
	const res = await proxy.$api({ url: config.YX_PIN_MUSIC_LS, data: param })
	if (res.status == 1 && res.data.music_ls) {
		musicList.value = res.data.music_ls
	}
}

const getDetail = async () => {
	console.log("props.detailID=", props.detailID)
	sLoading.value = true
	const res = await proxy.$api({ url: config.YY_EVENT_INFO, data: { id: props.detailID } }).finally(() => {
		setTimeout(() => {
			sLoading.value = false
		}, 200)
	})
	console.log("resxx=", res)
	if (res.status === 1 && res.data) {
		const data = res.data
		objectForm.value = {
			...objectForm.value,
			...data
		}
	}
}

const listLoading = ref(false)
const noMore = ref(false)
const pfrom = ref(1)
const pnum = ref(20)
const loadMoreData = async () => {
	pfrom.value++
	await getUserList()
}

const getUserList = async () => {
	listLoading.value = true
	const res = await proxy.$api({
		url: config.YY_EVENT_ULS, data: {
			id: props.detailID,
			pfrom: pfrom.value,
			pnum: pnum.value,
			st: 1, // 状态：1有效的，8伪造的
		}
	}).finally(() => {
		listLoading.value = false
	})
	if (res.status == 1 && res.data?.ls?.length > 0) {
		userList.value = [...userList.value, ...res.data.ls]
	}
	if (res.data?.ls?.length < pnum.value) {
		noMore.value = true
	}
	listLoading.value = false
}

// 修改 watch 实现
const detailsId = ref("")
watch(() => props.detailID, (newVal) => {
	setTimeout(() => {
		if (newVal) {
			detailsId.value = newVal
			getDetail()
			setTimeout(() => {
				getUserList()
			}, 200)
		}
	}, 200)
}, { immediate: true })

// Lifecycle hooks
onMounted(() => {
	pfrom.value = 1
	getMusicList()
})

const containerHeight = computed(() => {
	// Get the window height
	const windowHeight = window.innerHeight
	// Calculate the dynamic height based on the content above
	const headerHeight = 40 // Top header height
	const descriptionHeight = objectForm.value.type == 1 ? 360 : 360 // Approximate height of description section
	const dynamicHeight = headerHeight + descriptionHeight
	return `calc(100vh - ${dynamicHeight}px)`
})

defineExpose({
	getDetail,
	getUserList,
	pfrom
})

</script>

<style lang="scss" scoped>
.box-container {
	height: 100%;
	overflow: hidden;
	display: flex;
	flex-direction: column;
}

.box-content {
	flex: 1;
	overflow: hidden;
	overflow-y: auto;
}

.footer-content {
	height: 60px;
}

.addBoxTop {
	width: 100%;
	height: 40px;
	border-bottom: 2px solid #E4E7ED;
	margin-bottom: 15px;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.basc-info {
	margin-bottom: 5px;
	background-color: #fbfbfb;
	padding: 10px 15px;
	border-radius: 5px;
}

::v-deep .el-descriptions__body {
	background-color: transparent !important;
}

.poster-btn {
	border: 1px solid #f67fac;
	padding: 0 10px;
	border-radius: 5px;
	background-color: #fef0f0;
	color: #f67fac;
	cursor: pointer;
}

.avatar {
	height: 70px;
	width: 70px;
	border-radius: 50%;
}

.obj-avatar-box {
	height: 70px;
	width: 70px;
	border-radius: 6px;
	border: 1px solid #f5f9f9;
	overflow: hidden;
	background-color: #f5f9f9;
}

.obj-avatar {
	height: 100%;
	width: 100%;
	border-radius: 6px;

}

.card_box {
	::v-deep .el-card__body {
		padding: 10px !important;
	}
}

.tp_obj {
	box-sizing: border-box;
	background-color: #f1f4f8;
	padding: 5px 10px;
	border-radius: 5px;
	width: 130px;
	overflow: hidden;
}

.obj-ls-box {
	display: flex;
	flex-wrap: wrap;
	gap: 6px;
}

.obj-ls-item {
	background-color: #f8f9fa;
	padding: 8px 16px;
	border-radius: 4px;
	margin-right: 5px;
	margin-bottom: 5px;
	border: 1px solid #e9ecef;
}

.card_box {
	::v-deep .el-col {
		margin-bottom: 12px !important;

		&:last-child {
			margin-bottom: 0;
		}
	}
}

.poster-container {
	position: relative;

	.poster-bg {}
}
</style>